﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Communication.Model.acceleration;
using Communication.Model.configuration;
using Communication.Model.displacement;
using Communication.Model.helper;
using Communication.Model.netPacket;
using Communication.Model.speedData;
using Communication.Model.speedRealTVol;
using System.Diagnostics;
using System.Threading;

namespace TcpIpDemo
{
    public partial class Form1 : Form
    {
        ClientManager cm = new ClientManager();
        private int ChID = 0;
        DataTable dt = new DataTable();


        public Form1()
        {
            InitializeComponent();
            //cm.update += MessageInfoShow;
            cm.GetString += ReceivedString;
            cm.GetDisplacement += ReceivedDispalcement;
            cm.GetConfig += ReceivedConfig;
            cm.GetAccData += ReceivedAccData;
            cm.GetSpeed += ReceivedSpeedData;
            cm.GetSpeedVol += ReceivedSpeedVol;
            dataTableInit(16, 6);
            dataGridView1.DataSource = dt;
        }
        private void dataTableInit(int nrows, int ncols)
        {
            for (int i = 0; i < ncols; i++)
            {
                DataColumn dc = new DataColumn();
                dt.Columns.Add(dc);
            }
            for (int i = 0; i < nrows; i++)
            {
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
            }
        }
        /// <summary>
        /// 连接服务端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //bool isConnnected = cm.IsConnected(textBox2.Text, int.Parse(textBox3.Text));
            //MessageInfoShow(isConnnected.ToString());
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //cm.send("xxx.xx.xx.x");//向IP地址为"127.0.0.1"的下位机发送消
        }
        private void MessageInfoShow(string message)
        {
            //判断textbox4是否需要使用Invoke方法
            if (textBox1.IsHandleCreated && textBox1.InvokeRequired)
            {
                textBox1.Invoke(new Action<string>(MessageInfoShow), message);
                return;
            }
            textBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff ") + "接收到消息：" + message + Environment.NewLine);
        }
        private void ReceivedString(string msg)
        {
            MessageInfoShow(msg);
        }

        private void ReceivedDispalcement(DisplacementData data)
        {
            int size = Marshal.SizeOf(data);
            MessageInfoShow("位移数据包: " + size.ToString() + "byte");
            //更新chart
            updateChart1(data.CHDisData[ChID].ZDs);
        }
        private void ReceivedAccData(AccData acc)
        {
            int size = Marshal.SizeOf(acc);
            MessageInfoShow("加速度数据包: " + size.ToString() + "byte");
            //更新chart
            int id = int.Parse(textBox7.Text);
            updateChart2(acc.CHAccData[id].FFTAmpDB);
            //
            for (int i = 0; i < acc.CHAccData.Length; i++)
            {
                dt.Rows[i][3] = (i + 17).ToString();
                dt.Rows[i][4] = acc.CHAccData[i].TotalDB.ToString();
                dt.Rows[i][5] = acc.CHAccData[i].AverageVol.ToString();
            }
            dataGridView1.DataSource = dt;
        }
        private void ReceivedConfig(ACQParametersConfig config)
        {
            int size = Marshal.SizeOf(config);
            MessageInfoShow("系统配置数据包: " + size.ToString() + "byte");
        }
        public void ReceivedSpeedData(SpeedData data)
        {
            int size = Marshal.SizeOf(data);
            MessageInfoShow("转速数据包: " + size.ToString() + "byte");
            //string s = "";
            //for (int i = 0; i < 6; i++)
            //    s += ("转速"+i.ToString()+":"+data.Rpm[i].ToString()+",");
            //MessageInfoShow(s);
            for (int i = 0; i < data.ChSpeeds.Length; i++)
            {
                dt.Rows[i][0] = data.ChSpeeds[i].rpm.ToString();
            }
            dataGridView1.DataSource = dt;
        }
        public void ReceivedSpeedVol(SpeedRealTVol data)
        {
            int size = Marshal.SizeOf(data);
            MessageInfoShow("实时电压数据包: " + size.ToString() + "byte");
            for (int i = 0; i < data.ChVols.Length; i++)
            {
                dt.Rows[i][1] = data.ChVols[i].TopVolt.ToString();
                dt.Rows[i][2] = data.ChVols[i].BotmVolt.ToString();
            }
            dataGridView1.DataSource = dt;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            textBox2.Text = "192.168.2.64";
            textBox3.Text = "3000";
            textBox5.Text = "127.0.0.1";
            textBox6.Text = "5000";
            //chart2.ChartAreas[0].AxisX.IsLogarithmic = true;
        }
        private void updateChart1(float[] data)
        {
            if (chart1.IsHandleCreated && chart1.InvokeRequired)
            {
                chart1.Invoke(new Action<float[]>(updateChart1), data);
                return;
            }
            chart1.Series[0].Points.DataBindY(data);
        }
        private void updateChart2(float[] data)
        {

            if (chart2.IsHandleCreated && chart1.InvokeRequired)
            {
                chart2.Invoke(new Action<float[]>(updateChart2), data);
                return;
            }
            float[] x = new float[65536];
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = (i + 1) * 25600.0f / 131072.0f;
                //data[i] = Convert.ToSingle(Math.Log10(data[i]) * 20 + 120.0f);
            }
            chart2.ChartAreas[0].Axes[0].IsLogarithmic = true;
            chart2.Series[0].Points.DataBindXY(x, data);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            cm.sendString(textBox2.Text, textBox4.Text);
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            MyTcpIp.configuration.ACQParametersConfig configdata = new MyTcpIp.configuration.ACQParametersConfig();
            DisplacementData dis = new DisplacementData();
            int len = Marshal.SizeOf(dis);
            //NetPacketHead head = new NetPacketHead();
            //int len2 = 
            string ip = textBox5.Text;//"192.168.2.10"
            string[] ipStr = ip.Split('.');
            byte[] ipByte = new byte[4];
            for (int i = 0; i < ipByte.Length; i++)
            {
                ipByte[i] = Byte.Parse(ipStr[i]);
            }
            configdata.IPAddress = ipByte;
            configdata.ClientPortNum = long.Parse(textBox6.Text);
            initializeACQData(configdata);
            //NetPacket packet = new NetPacket()
            //{
            //    Data = configdata,
            //    PacketHead = new NetPacketHead()
            //    {
            //        Version = 1,
            //        PType = PType.ACQParametersConfig
            //    }
            //};
            MyTcpIp.netPacket.NetPacket packet1 = new MyTcpIp.netPacket.NetPacket();
            MyTcpIp.netPacket.NetPacketHead PacketHead1 = new MyTcpIp.netPacket.NetPacketHead();
            PacketHead1.Version = 1;
            PacketHead1.PacketType = MyTcpIp.packetType.PacketType.ACQParametersConfig;
            packet1.DataPacket = configdata;
            packet1.NetPacketHead = PacketHead1;

            cm.SendNetPacket("127.0.0.1", packet1);
        }
        #region【配置结构体赋值】
        private void initializeACQData(MyTcpIp.configuration.ACQParametersConfig configdata)
        {

            configdata.AcquisitionType = 0;
            configdata.BlackboxAfterEvent = 0;
            configdata.BlackboxBeforeEvent = 0;
            configdata.BlackBoxSavFre = 0;
            configdata.BlackBoxSDownLimit = 0;
            configdata.BlackBoxSUpLimit = 0;
            configdata.HourDBInterval = 0;
            configdata.LocalSave = 0;
            configdata.MonthDBInterval = 0;
            configdata.StartSpeed = 0;
            configdata.StopSpeed = 0;
            configdata.SystemDebug = 0;
            configdata.UIRefreshFrequency = 0;
            configdata.VariableLoadDB = 0;
            configdata.VerDriver = 0;
            configdata.VerFPGACollect = 0;
            configdata.VerFPGAMain = 0;
            configdata.VerSysSoftware = 0;
            configdata.WeekDBInterval = 0;
            configdata.YearDBInterval = 0;
            configdata.DayDBInterval = 0;

            float[] gearJianxaing = new float[8];
            float[] gearMax = new float[8];
            float[] gearMin = new float[8];
            float[] jianXiangCaoMax = new float[8];
            float[] jianXiangCaoMin = new float[8];

            for (int i = 0; i < 8; i++)
            {

                gearJianxaing[i] = 0;
                gearMax[i] = 0;
                gearMin[i] = 0;
                jianXiangCaoMax[i] = 0;
                jianXiangCaoMin[i] = 0;
            }

            MyTcpIp.configuration.ChannelConfig channelConfig = InitializeCHConfig();
            MyTcpIp.configuration.SpeedConfig speedConfig = InitializeSpeedConfig();
            MyTcpIp.configuration.TestPoint testPoint = InitializeTestPoint();
            MyTcpIp.configuration.TriAccTestPointCon triAccTestPointCon = InitializeTriAccTestPointCon();

            MyTcpIp.configuration.ChannelConfig[] channelConfig_Data = new MyTcpIp.configuration.ChannelConfig[32];
            for (int i = 0; i < 32; i++)
            {
                channelConfig_Data[i] = channelConfig;
            }
            configdata.ChannelConfig_Data = channelConfig_Data;


            MyTcpIp.configuration.SpeedConfig[] speedConfigt_Data = new MyTcpIp.configuration.SpeedConfig[6];
            for (int i = 0; i < 6; i++)
            {
                speedConfigt_Data[i] = speedConfig;
            }
            configdata.SpeedConfigt_Data = speedConfigt_Data;

            MyTcpIp.configuration.TestPoint[] testPoint_Data = new MyTcpIp.configuration.TestPoint[16];
            MyTcpIp.configuration.TriAccTestPointCon[] triAccTestPointConfig_Data = new MyTcpIp.configuration.TriAccTestPointCon[16];
            for (int i = 0; i < 16; i++)
            {
                testPoint_Data[i] = testPoint;
                triAccTestPointConfig_Data[i] = triAccTestPointCon;
            }
            configdata.TestPoint_Data = testPoint_Data;
            configdata.TriAccTestPointConfig_Data = triAccTestPointConfig_Data;

        }

        private TriAccTestPointCon InitializeTriAccTestPointCon()
        {
            MyTcpIp.configuration.TriAccTestPointCon triAccTestPointCon = new MyTcpIp.configuration.TriAccTestPointCon();

            char[] testpointName = new char[128];

            for (int i = 0; i < 128; i++)
            {
                testpointName[i] = char.Parse("0");
            }

            triAccTestPointCon.TestpointName = testpointName;

            triAccTestPointCon.TestPointXChannelID = 0;
            triAccTestPointCon.TestPointYChannelID = 0;
            triAccTestPointCon.TestPointZChannelID = 0;

            return triAccTestPointCon;
        }

        private TestPoint InitializeTestPoint()
        {
            MyTcpIp.configuration.TestPoint testPoint = new TestPoint();
            testPoint.bearhori = 0;
            testPoint.bearhousx = 0;
            testPoint.bearhousy = 0;
            testPoint.bearveri = 0;
            testPoint.iniaxlex = 0;
            testPoint.iniaxley = 0;

            char[] testPointName = new char[128];
            for (int i = 0; i < 128; i++)
            {
                testPointName[i] = char.Parse("0");
            }
            testPoint.TestPointName = testPointName;


            testPoint.TestPointXChannelID = 0;
            testPoint.TestPointYChannelID = 0;

            return testPoint;
        }

        private MyTcpIp.configuration.SpeedConfig InitializeSpeedConfig()
        {
            MyTcpIp.configuration.SpeedConfig speedConfig = new MyTcpIp.configuration.SpeedConfig();
            speedConfig.CompareVol = 0;
            speedConfig.GearTeethNum = 0;
            speedConfig.KeyPhaseID = 0;

            char[] keyPhaseName = new char[128];
            for (int i = 0; i < 128; i++)
            {
                keyPhaseName[i] = char.Parse("0");
            }
            speedConfig.KeyPhaseName = keyPhaseName;

            speedConfig.RotationDirection = 0;
            speedConfig.RunMod = 0;
            speedConfig.KeyPhaseAngle = 0;

            return speedConfig;
        }

        private MyTcpIp.configuration.ChannelConfig InitializeCHConfig()
        {
            MyTcpIp.configuration.ChannelConfig channelConfig = new MyTcpIp.configuration.ChannelConfig();

            char[] band1 = new char[20];
            char[] band2 = new char[20];
            char[] band3 = new char[20];
            char[] channelName = new char[20];
            for (int i = 0; i < 20; i++)
            {
                band1[i] = char.Parse("0");
                band2[i] = char.Parse("0");
                band3[i] = char.Parse("0");
                channelName[i] = char.Parse("0");
            }
            channelConfig.Band1 = band1;
            channelConfig.Band2 = band2;
            channelConfig.Band3 = band3;
            channelConfig.ChannelName = channelName;


            channelConfig.Band1IsUser = 0;
            channelConfig.Band1RedValue = 0;
            channelConfig.Band1YellowValue = 0;
            channelConfig.Band2IsUser = 0;
            channelConfig.Band2RedValue = 0;
            channelConfig.Band2YellowValue = 0;
            channelConfig.Band3IsUser = 0;
            channelConfig.Band3RedValue = 0;
            channelConfig.Band3YellowValue = 0;
            channelConfig.ChannelId = 0;
            channelConfig.HalfAmplitudeIsUser = 0;
            channelConfig.HalfAmplitudeRedValue = 0;
            channelConfig.HalfAmplitudeYellowValue = 0;
            channelConfig.InstallationAngle = 0;
            channelConfig.Linearity = 0;
            channelConfig.LLimit1 = 0;
            channelConfig.LLimit2 = 0;
            channelConfig.LLimit3 = 0;
            channelConfig.OffsetValue = 0;
            channelConfig.OneAmplitudeIsUser = 0;
            channelConfig.OneAmplitudeRedValue = 0;
            channelConfig.OneAmplitudeYellowValue = 0;
            channelConfig.PassAmplitudeIsUser = 0;
            channelConfig.PassAmplitudeRedValue = 0;
            channelConfig.PassAmplitudeYellowValue = 0;
            channelConfig.Sensitivity = 0;
            channelConfig.SensorType = 0;
            channelConfig.TwoAmplitudeIsUser = 0;
            channelConfig.TwoAmplitudeRedValue = 0;
            channelConfig.TwoAmplitudeYellowValue = 0;
            channelConfig.ULimit1 = 0;
            channelConfig.ULimit2 = 0;
            channelConfig.ULimit3 = 0;
            channelConfig.ZeroOffset = 0;

            return channelConfig;
        }
        #endregion
        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            //ChID = int.Parse(textBox7.Text);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Random rd = new Random();  //无参即为使用系统时钟为种子
            //dt.Rows[0][0] = rd.Next().ToString();
            //dataGridView1.DataSource = dt;
            //string s = "-----VIB DATA-----";
            //byte[] buffer = new SerializeHelper().SerializeString<string>(s);
            //WebCommunication.uploadData(buffer);
            ////初始化
            //DisplacementData data = new DisplacementData();
            //data.CHDisData = new CHDisplacementData[16];
            //for (int i = 0; i < 16; i++)
            //{
            //    data.CHDisData[i].ZDs = new float[1024];
            //}
            //data.Year = (ushort)System.DateTime.Now.Year;
            //data.Month = (byte)System.DateTime.Now.Month;
            //data.Day = (byte)System.DateTime.Now.Day;
            //data.Hour = (byte)System.DateTime.Now.Hour;
            //data.Minute = (byte)System.DateTime.Now.Minute;
            //data.Second = (byte)System.DateTime.Now.Second;
            //data.CHDisData[0].PK2PK = 1.234f;
            ////网络发送
            //byte[] buffer = new SerializeHelper().Serialize<DisplacementData>(data);
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            ////耗时巨大的代码
            //string filepath = @"C:\Users\jz\Desktop\DispData\";
            //WebCommunication wc = new WebCommunication();
            //wc.data2file(filepath, data);
            //sw.Stop();
            //TimeSpan ts1 = sw.Elapsed;//100ms
            ////文件上传，开辟新线程


        }

        private void button5_Click(object sender, EventArgs e)
        {
            //WebCommunication wc = new WebCommunication();
            //string dir = @"C:\Users\jz\Desktop\DispData\";
            //wc.dir = dir;
            //Thread th = new Thread(new ThreadStart(wc.StartUpload)); //创建线程                     
            //th.Start(); //启动线程
            //button5.Enabled = false;
        }

    }
}
